package ce.com.cenewbluesdk.uitl;

public class CRC16 {
    private CRC16() {
    }

    public static int crc16(byte[] data) {
        if (data == null)
            return 0;

        int crc16 = 0;
        for (int i = 0; i < data.length; ++i) {
            crc16 = crc_dsp(crc16, data[i]);
        }

        return (crc16 & 0x0000ffff);
    }
    public static int crc16(byte[] data,int index) {
        if (data == null)
            return 0;

        int crc16 = 0;
        for (; index < data.length; ++index) {
            crc16 = crc_dsp(crc16, data[index]);
        }

        return (crc16 & 0x0000ffff);
    }

    private static int crc_dsp(int reg, short data_crc) {
        int msb;
        int data;
        int gx = 0x8005, i = 0;

        data = (int) data_crc;
        data = data << 8;
        reg = reg ^ data;

        do {
            msb = reg & 0x8000;
            reg = reg << 1;
            if (msb == 0x8000) {
                reg = reg ^ gx;
            }
            i++;
        }
        while (i < 8);

        return (reg);
    }

}


